In [1]:
# Initializa a, b and c
a = 100
b = 0.1
c = 0.2
# Compute the two values
d_0 = a*b + a*c
d_1 = a*(b + c)
print(d_0)
print(d_1)
print(d_0 == d_1)
For the polynomial
\begin{align} f(x, y) &= (x + y)^{6} \\ &= x^6 + 6x^{5}y + 15x^{4}y^{2} + 20x^{3}y^{3} + 15x^{2}y^{4} + 6xy^{5} + y^{6} \end{align}compute $f$ using: (a) the compact form $(x + y)^{6}$; and (b) the expanded form for:
and compare the number of significant digits for which the answers are the same. For the second case compare the computed and analytical solutions.
Which approach would you recommend for computing this expression?
I would choose the compact form since, containing less terms, it minimizes the possibility of errors due to the floating point representation of numbers
In [2]:
# Initialize x and y
x, y = 10, 10.1
print('x and y values:' ,x, y)
# Calculate the two expressions
f1 = (x + y)**6
f2 = x**6 + 6*x**5*y + 15*x**4*y**2 + 20*x**3*y**3 + 15*x**2*y**4 + 6*x*y**5 + y**6
print('Compact form:', f1, '\nExpanded form:', f2, '\nDifference:', f1-f2)
print('\n---------------------------------------------------------\n')
# Initialize x and y
x, y = 10, -10.1
print('x and y values:' ,x, y)
# Calculate the two expressions
f1 = (x + y)**6
f2 = x**6 + 6*x**5*y + 15*x**4*y**2 + 20*x**3*y**3 + 15*x**2*y**4 + 6*x*y**5 + y**6
print('Compact form:', f1, '\nExpanded form:', f2, '\nDifference:', f1-f2)
Consider the expression
$$ f = \frac{1}{\sqrt{x^2 - 1} - x} $$When $x$ is very large, the denominator approaches zero, which can cause problems.
Try rephrasing the problem and eliminating the fraction by multiplying the numerator and denominator by $\sqrt{x^2 - 1} + x$ and evaluate the two versions of the expression when:
In [3]:
# Import math to compute square root
import math
The expression obtained by multiplying the numerator and denominator by $\sqrt{x^2 - 1} + x$ is
$$ f = -\sqrt{x^2 - 1} - x. $$Let's try the first value $1 \times 10^{7}$
In [4]:
# Initialize x
x = 1e7
# Compute the two expressions
f1 = 1 / (math.sqrt(x**2-1) - x)
f2 = -math.sqrt(x**2-1) - x
print('Result of the first expression:', f1, '\nResult of the second expression:', f2)
The second expression is more precise; moreover it avoids the risk of a division by zero error:
In [5]:
# Initialize x
x = 1e9
# This gives division by zero error
f1 = 1 / (math.sqrt(x**2-1) - x)
print('Result of the first expression:', f1)
In [6]:
# Initialize x
x = 1e9
# This doesn't
f2 = (math.sqrt(x**2-1) + x)
print('Result of the second expression:', f2)